//
//  ZKVCRead.m
//  ZAKER
//
//  Created by Anyfish002 on 17/2/20.
//  Copyright © 2017年 yaohongchao. All rights reserved.
//

#import "ZKVCRead.h"
#import "ZKReadModel.h"
#import "ZKHelper.h"

@interface ZKVCRead ()
@property(nonatomic,weak) UIWebView *webView;
@property(nonatomic,strong) ZKReadModel *readModel;
@end

@implementation ZKVCRead

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
    [self setupData];
    // Do any additional setup after loading the view.
}

-(void)setup{
    self.view.backgroundColor = [UIColor whiteColor];
    UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
    webView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:webView];
    self.webView = webView;
    
}

-(void)setupData{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURL *URL = [NSURL URLWithString:self.article.full_url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    WS(weakSelf);
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            
        } else {
            ZKReadModel *readModel = [[ZKReadModel alloc]initWithDictionary:responseObject];
            weakSelf.readModel = readModel;
            [weakSelf loadImages];
            NSString *string = @"<html>";
            string = [string stringByAppendingString:readModel.data.content];
            string = [string stringByAppendingString:@"</html>"];
            string = [weakSelf replaceImagePath];
            [weakSelf.webView loadHTMLString:string baseURL:[NSURL URLWithString:[ZKHelper getCachePath]]];
        }
    }];
    [dataTask resume];
}

-(NSString*)replaceImagePath{
    NSString *html = self.readModel.data.content;
    for (ZKReadMedia *media in self.readModel.data.media) {
        NSString *str = [[SDImageCache sharedImageCache] defaultCachePathForKey:media.url];
        NSRange range = [html rangeOfString:@"article_html_content_loading.png"];
        html = [html stringByReplacingCharactersInRange:range withString:str];
    }
    return html;
}

-(void)loadImages{
    [[SDImageCache sharedImageCache] makeDiskCachePath:[ZKHelper getCachePath]];
    for (ZKReadMedia *media in self.readModel.data.media) {
        [[SDWebImageDownloader sharedDownloader]downloadImageWithURL:[NSURL URLWithString:media.url] options:SDWebImageDownloaderHighPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            [[SDImageCache sharedImageCache] storeImage:image forKey:media.url];
        }];
    }
}

@end
